//
//  WLRouterWiFiSubController.m
//  WanLian
//
//  Created by muzhuang on 2018/10/18.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLRouterWiFiSubController.h"
#import "WLRouterEncryptPopView.h"
#import "WLRouterNetSetCell.h"
#import "AppDelegate.h"
#import "WLRouterRestartView.h"

@interface WLRouterWiFiSubController ()<UITableViewDelegate,UITableViewDataSource>//,RouterSocketDelegate>
{
    BOOL isShowRestartView;
}

@property (nonatomic, strong) UITableView *tbWiFiSet;
//@property (nonatomic, assign) NSInteger encryptType;
@property (nonatomic, assign) BOOL  isFourHide;
@property (nonatomic, assign) BOOL  isFiveHide;
@property (nonatomic, assign) BOOL  isGuestHide;
@property (nonatomic, strong) NSMutableDictionary *dictFourWiFi;
@property (nonatomic, strong) NSMutableDictionary *dictFiveWiFi;
@property (nonatomic, strong) NSMutableDictionary *dictGuestWiFi;

@end

@implementation WLRouterWiFiSubController

- (void)dealloc
{
//    [[WLSocketManager sharedSocketManager] removeDelegate:self];
    [[WLSocketManager sharedSocketManager] removeDelegate:self delegateQueue:dispatch_get_main_queue()];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    _encryptType = 1;
//    if (_wifiType==0) {
//        _isHide = self.wifiModel.twoWifiForce;
//    }
//    else if (_wifiType==1)
//    {
//        _isHide = self.wifiModel.fiveWifiForce;
//    }
//    else
//    {
//        _isHide = self.wifiModel.customerWifiForce;
//    }
    _tbWiFiSet = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tbWiFiSet.backgroundColor = wlUIColorRGB(0xFAFAFA);
    _tbWiFiSet.delegate = self;
    _tbWiFiSet.dataSource = self;
    _tbWiFiSet.rowHeight = WLScaleX(58);
    if (@available(iOS 11.0, *)) {
        _tbWiFiSet.estimatedSectionHeaderHeight = 0;
        _tbWiFiSet.estimatedSectionFooterHeight = 0;
    }
    [self.view addSubview:_tbWiFiSet];
    _tbWiFiSet.scrollEnabled = NO;
    WLWkSelf
    [_tbWiFiSet mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    
    UIButton *btnSave = [[UIButton alloc] initWithFrame:CGRectMake(WLScaleX(16), WLScaleX(20+58*4+40), WIDTH_SCREEN_WL-WLScaleX(32), WLScaleX(47))];
    btnSave.layer.cornerRadius = 5;
    btnSave.layer.masksToBounds = YES;
    btnSave.titleLabel.font = [WLCommonTool fontTypePingFangSCMedium:16];
    [btnSave setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btnSave addTarget:self action:@selector(saveWiFiSetAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:btnSave];
    [WLCommonTool addGradientColor:btnSave fromColor:wlblueColor toColor:wlUIColorRGB(0x2292F5)];
    [btnSave setTitle:@"保存设置" forState:UIControlStateNormal];
    
//    [[WLSocketManager sharedSocketManager] addDelegate:self];
    [[WLSocketManager sharedSocketManager] addDelegate:self delegateQueue:dispatch_get_main_queue()];
    [self receiveRouterWiFiSet];
}

- (void)receiveRouterWiFiSet
{
    NSDictionary *dict;
    if (_wifiType==0) {
        dict = @{@"type":@"DEVICE_TWOWIFIGET_REQ",@"content":@""};
//        self.dictWiFi = @{@"username":@"admin",@"password":@"888888",@"eryType":@"psk",@"hide":[NSNumber numberWithBool:YES]};

    }
    else if (_wifiType==1)
    {
        dict = @{@"type":@"DEVICE_FIVEWIFIGET_REQ",@"content":@""};
    }
    else
    {
        dict = @{@"type":@"DEVICE_CUSTOMERWIFIGET_REQ",@"content":@""};
    }
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
}

- (void)receiveRouterWifiAgain
{
    NSDictionary *dict;
    if (_wifiType==0&&self.dictFourWiFi==nil)
    {
        dict = @{@"type":@"DEVICE_TWOWIFIGET_REQ",@"content":@""};
    }
    else if (_wifiType==1&&self.dictFiveWiFi==nil)
    {
        dict = @{@"type":@"DEVICE_FIVEWIFIGET_REQ",@"content":@""};
    }
    else if (_wifiType==2&&self.dictGuestWiFi==nil)
    {
        dict = @{@"type":@"DEVICE_CUSTOMERWIFIGET_REQ",@"content":@""};
    }
    if (dict !=nil) {
        [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
    }
}

#pragma mark - 接收消息代理
- (void)didReceiveMessage:(WLSocketModel *)msgModel withTag:(long)tag
{
    if ([msgModel.type isEqualToString:@"DEVICE_TWOWIFIGET_REP"])
    {
        if (msgModel.content != nil) {
            NSData *jsonData = [msgModel.content dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                options:NSJSONReadingMutableContainers
                                                                  error:&err];
            self.dictFourWiFi = [[NSMutableDictionary alloc] initWithDictionary:dic];
            _isFourHide = [dic[@"hide"] boolValue];
            [self.tbWiFiSet reloadData];
        }
    }
    else if ([msgModel.type isEqualToString:@"DEVICE_FIVEWIFIGET_REP"])
    {
        NSData *jsonData = [msgModel.content dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        self.dictFiveWiFi = [[NSMutableDictionary alloc] initWithDictionary:dic];
        _isFiveHide = [dic[@"hide"] boolValue];
        [self.tbWiFiSet reloadData];
    }
    else if ([msgModel.type isEqualToString:@"DEVICE_CUSTOMERWIFIGET_REP"])
    {
        NSData *jsonData = [msgModel.content dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        self.dictGuestWiFi = [[NSMutableDictionary alloc] initWithDictionary:dic];
        _isGuestHide = [dic[@"hide"] boolValue];
        [self.tbWiFiSet reloadData];
    }
    else if ([msgModel.type isEqualToString:@"COMMON_SUCCESS"])
    {
//        [self showHUDMessage:@"设置成功"];
        if (isShowRestartView) {
            [[WLSocketManager sharedSocketManager] userManualdisconnect];
            isShowRestartView = NO;
            WLWkSelf
            WLRouterRestartView *restartView = [[WLRouterRestartView alloc] init];
            restartView.okAction = ^{
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            };
            [restartView show];
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:[NSDate date] forKey:@"restartTime"];
            [userDefaults synchronize];
            AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
            [appDelegate linkRouterTest:30];
        }
    }
}

- (void)saveWiFiSetAction
{
    [self.view endEditing:YES];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    WLRouterNetSetCell *cell = (WLRouterNetSetCell *)[self.tbWiFiSet cellForRowAtIndexPath:indexPath];
    NSString *strName= cell.textNetInfo.text;
    NSIndexPath *indexPath1 = [NSIndexPath indexPathForRow:1 inSection:0];
    WLRouterNetSetCell *cell1 = (WLRouterNetSetCell *)[self.tbWiFiSet cellForRowAtIndexPath:indexPath1];
    if (strName.length<1||strName.length>21) {
        [self showHUDMessage:@"请输入正确的WiFi名称"];
        return;
    }
    
    NSIndexPath *indexWAP = [NSIndexPath indexPathForRow:3 inSection:0];
    UITableViewCell *cellWAP = [self.tbWiFiSet cellForRowAtIndexPath:indexWAP];
    NSString *strWap = @"psk2";
    if ([cellWAP.detailTextLabel.text isEqualToString:@"无密码"]) {
        strWap = @"none";
    }
    else if ([cellWAP.detailTextLabel.text isEqualToString:@"WPA/WPA2"])
    {
        strWap = @"psk-mixed";
    }
    
    NSString *strPwd= cell1.textNetInfo.text;
    if ([strWap isEqualToString:@"none"]==NO&&(strPwd.length<8||strPwd.length>16)) {
        [self showHUDMessage:@"WiFi密码在8到16位之间"];
        return;
    }
    
    BOOL isHide;
    NSString *reqType;
    if (_wifiType==0) {
        reqType = @"DEVICE_TWOWIFI_SET";
        isHide = _isFourHide;
    }
    else if (_wifiType==1)
    {
        reqType = @"DEVICE_FIVEWIFI_SET";
        isHide = _isFiveHide;
    }
    else
    {
        reqType = @"DEVICE_CUSTOMERWIFI_SET";
        isHide = _isGuestHide;
    }
    NSDictionary *paramWiFi = @{@"password":strPwd,@"username":strName,@"hide":@(isHide),@"eryType":strWap};
//    if (_wifiType==0) {
//        paramWiFi = @{@"hasTwoConfig":[NSNumber numberWithBool:YES],@"twoWifiPassWord":strPwd,@"twoWifiAccount":strName,@"twoWifiForce":@(_isHide),@"twoWifiLocktype":strWap};
//    }
//    else if (_wifiType==1)
//    {
//        paramWiFi = @{@"hasFiveConfig":[NSNumber numberWithBool:YES],@"fiveAccount":strName,@"fiveWifiPassWord":strPwd,@"fiveWifiLocktype":strWap,@"fiveWifiForce":@(_isHide)};
//    }
//    else
//    {
//        paramWiFi = @{@"hasCustomerConfig":[NSNumber numberWithBool:YES],@"customerWifiAccount":strName,@"customerWifiPassWord":strPwd,@"customerWifiLocktype":strWap,@"customerWifiForce":@(_isHide)};
//    }
    NSError *parseError;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:paramWiFi options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *strContent = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSDictionary *dict = @{@"type":reqType,@"content":strContent};
    [[WLSocketManager sharedSocketManager] sendMessage:dict timeOut:-1 tag:0];
    isShowRestartView = YES;
//    WLWkSelf
//    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"device/config/edit" withParamsDic:paramWiFi success:^(NSDictionary *successDict) {
//        [weakSelf showHUDMessage:successDict[@"message"]];
//    } failure:^(NSString *errorMsg, NSInteger errorTag) {
//        [weakSelf showHUDMessage:errorMsg];
//    } error:^(NSError *error) {
//
//    } inView:self.view];
}

#pragma mark - UITableView
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return WLScaleX(20);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = indexPath.row;
    if (row<2)
    {
        static NSString *strNet = @"netCell";
        WLRouterNetSetCell *cell = [tableView dequeueReusableCellWithIdentifier:strNet];
        if (!cell) {
            cell = [[WLRouterNetSetCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strNet];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cell.textNetInfo.text = @"";
        if (row==0) {
            cell.labTitle.text = @"名称";
            cell.textNetInfo.placeholder = @"请设置WiFi名称";
//            cell.textNetInfo.text = self.dictWiFi[@"username"];
            if (_wifiType==0) {
                cell.textNetInfo.text = self.dictFourWiFi[@"username"];
            }
            else if (_wifiType==1)
            {
                cell.textNetInfo.text = self.dictFiveWiFi[@"username"];
            }
            else
            {
                cell.textNetInfo.text = self.dictGuestWiFi[@"username"];
            }
        }
        else
        {
            cell.textNetInfo.enabled = YES;
            cell.labTitle.text = @"密码";
            cell.textNetInfo.placeholder = @"请设置WiFi密码";
            NSString *strType;
            if (_wifiType==0) {
                cell.textNetInfo.text = self.dictFourWiFi[@"password"];
                strType = self.dictFourWiFi[@"eryType"];
            }
            else if (_wifiType==1)
            {
                cell.textNetInfo.text = self.dictFiveWiFi[@"password"];
                strType = self.dictFiveWiFi[@"eryType"];
            }
            else
            {
                cell.textNetInfo.text = self.dictGuestWiFi[@"password"];
                strType = self.dictGuestWiFi[@"eryType"];
            }
            if ([strType isEqualToString:@"none"]) {
                cell.textNetInfo.enabled = NO;
                cell.textNetInfo.text = @"";
                cell.textNetInfo.placeholder = @"无需设置密码";
                cell.accessoryView = nil;
            }
            else
            {
                cell.textNetInfo.secureTextEntry = YES;
                UIButton *btnEye = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
                [btnEye setImage:[UIImage imageNamed:@"eye_net_close"] forState:UIControlStateNormal];
                [btnEye setImage:[UIImage imageNamed:@"eye_net_open"] forState:UIControlStateSelected];
                [btnEye addTarget:self action:@selector(openOrCloseAction:) forControlEvents:UIControlEventTouchUpInside];
                btnEye.selected = NO;
                cell.accessoryView = btnEye;
            }
        }
        return cell;
    }
    
    static NSString *strWiFi = @"WiFiCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strWiFi];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:strWiFi];
        cell.textLabel.font = [WLCommonTool fontTypePingFangSCRegular:17];
        cell.textLabel.textColor = wlBlackColor;
        cell.detailTextLabel.font = [WLCommonTool fontTypePingFangSCRegular:14];
        cell.detailTextLabel.textColor = wlLightTextColor;
    }
    cell.detailTextLabel.text = @"";
    if (row==2) {
        cell.textLabel.text = @"隐藏网络";
        UISwitch *btnSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 40, WLScaleX(14))];
//        btnSwitch.transform = CGAffineTransformMakeScale(0.75, 0.75);
        btnSwitch.onTintColor = wlblueColor;//wlRGBACOLOR(26, 89, 226, 0.6);
//        btnSwitch.thumbTintColor = wlblueColor;
        [btnSwitch addTarget:self action:@selector(hideNetAction:) forControlEvents:UIControlEventValueChanged];
//        btnSwitch.on = _isHide;
        if (_wifiType==0) {
            btnSwitch.on = _isFourHide;
        }
        else if (_wifiType==1)
        {
            btnSwitch.on = _isFiveHide;
        }
        else
        {
            btnSwitch.on = _isGuestHide;
        }
        cell.accessoryView = btnSwitch;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    else
    {
        cell.textLabel.text = @"加密类型";
        if (_wifiType==0) {
            if ([self.dictFourWiFi[@"eryType"] isEqualToString:@"none"]) {
                cell.detailTextLabel.text = @"无密码";
            }
            else if ([self.dictFourWiFi[@"eryType"] isEqualToString:@"psk-mixed"])
            {
                cell.detailTextLabel.text = @"WPA/WPA2";
            }
            else
            {
                cell.detailTextLabel.text = @"WPA2";
            }
        }
        else if (_wifiType==1)
        {
            if ([self.dictFiveWiFi[@"eryType"] isEqualToString:@"none"]) {
                cell.detailTextLabel.text = @"无密码";
            }
            else if ([self.dictFiveWiFi[@"eryType"] isEqualToString:@"psk-mixed"])
            {
                cell.detailTextLabel.text = @"WPA/WPA2";
            }
            else
            {
                cell.detailTextLabel.text = @"WPA2";
            }
        }
        else
        {
            if ([self.dictGuestWiFi[@"eryType"] isEqualToString:@"none"]) {
                cell.detailTextLabel.text = @"无密码";
            }
            else if ([self.dictGuestWiFi[@"eryType"] isEqualToString:@"psk-mixed"])
            {
                cell.detailTextLabel.text = @"WPA/WPA2";
            }
            else
            {
                cell.detailTextLabel.text = @"WPA2";
            }
        }
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==3) {
        WLWkSelf
        [WLRouterEncryptPopView showEncryViewAction:^(NSInteger index) {
            [weakSelf updateEncryptCell:index];
        }];
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}

- (void)updateEncryptCell:(NSInteger)index
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
    UITableViewCell *cell = [self.tbWiFiSet cellForRowAtIndexPath:indexPath];
    NSString *strType = @"";
    NSString *strErytype;
    if (index==1) {
        strType = @"WPA2";
        strErytype = @"psk2";
    }
    else if (index==2)
    {
        strType = @"WPA/WPA2";
        strErytype = @"psk-mixed";
    }
    else if (index==3)
    {
        strType = @"无密码";
        strErytype = @"none";
    }
    cell.detailTextLabel.text = strType;
    if (strErytype) {
        if (_wifiType==0)
        {
            self.dictFourWiFi[@"eryType"] = strErytype;
        }
        else if (_wifiType==1)
        {
            self.dictFiveWiFi[@"eryType"] = strErytype;
        }
        else
        {
            self.dictGuestWiFi[@"eryType"] = strErytype;
        }
        NSIndexPath *indexs = [NSIndexPath indexPathForRow:1 inSection:0];
        [self.tbWiFiSet reloadRowsAtIndexPaths:@[indexs] withRowAnimation:UITableViewRowAnimationNone];
    }
}

- (void)openOrCloseAction:(UIButton *)btnEye
{
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
    WLRouterNetSetCell *cell = (WLRouterNetSetCell *)[self.tbWiFiSet cellForRowAtIndexPath:indexPath];
    cell.textNetInfo.secureTextEntry = btnEye.selected;
    btnEye.selected = !btnEye.selected;
}

- (void)hideNetAction:(UISwitch *)btnSwitch
{
    BOOL isHide = btnSwitch.on;
    if (_wifiType==0) {
        _isFourHide = isHide;
    }
    else if (_wifiType==1)
    {
        _isFiveHide = isHide;
    }
    else
    {
        _isGuestHide = isHide;
    }
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
